//
//  File.swift
//
//
//  Created by didi on 2022/9/13.
//

import Vapor

public protocol CreateController: ModelController {
    associatedtype CreateContext

    func createAccess(_ req: Request) async throws -> Bool
    func beforeCreate(_ req: Request, _ model: DatabaseModel, _ context: CreateContext) async throws
    func afterCreate(_ req: Request, _ model: DatabaseModel, _ context: CreateContext) async throws
    func creating(_ req: Request, _ model: DatabaseModel, _ context: CreateContext) async throws
}

public extension CreateController {
    func createAccess(_ req: Request) async throws -> Bool {
        try await req.checkAccess(for: ApiModel.permission(for: .create))
    }

    func beforeCreate(_ req: Request, _ model: DatabaseModel, _ context: CreateContext) async throws {
    }

    func afterCreate(_ req: Request, _ model: DatabaseModel, _ context: CreateContext) async throws {
    }

    func creating(_ req: Request, _ model: DatabaseModel, _ context: CreateContext) async throws {
        try await model.create(on: req.db)
    }
}
